<?php

namespace app\common\model;

use app\common\controller\Queue;
use app\common\library\Auth;
use app\common\service\OrderService;
use app\common\service\UserService;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{
	
	use SoftDelete;
	
	
	// 表名
	protected $name = 'order';
	
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	
	// 定义时间戳字段名
	protected $createTime = 'create_time';
	protected $updateTime = 'update_time';
	protected $deleteTime = 'delete_time';
	
	// 追加属性
	protected $append = [
		'pay_time_text',
		'shipping_time_text',
		'sign_time_text',
		'status_text',
		'order_type_text',
		'pay_status_text',
		'shipping_status_text',
		'close_reason',
		'area_text',
		'sign_type_text',
		'rebate_status_text',
	];
	
	const STATUS_WAIT = 0;
	const STATUS_GROUP = 1;
	const STATUS_SIGN = 2;
	const STATUS_SUCCESS = 3;
	const STATUS_CLOSE = -1;
	const STATUS_WAIT_SHIPPING = 4;
	const STATUS_WAIT_SIGN = 5;
	
	public static $statusList = [
		self::STATUS_GROUP => '拼团中',
		self::STATUS_WAIT => '待付款',
		self::STATUS_SIGN => '待核销',
		self::STATUS_SUCCESS => '已完成',
		self::STATUS_CLOSE => '已关闭',
		self::STATUS_WAIT_SHIPPING => '待发货',
		self::STATUS_WAIT_SIGN => '待签收 '
	];
	
	public function getStatusTextAttr($value, $data)
	{
		$value = $value ?: $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}
	
	const TYPE_NORMAL = 1;
	const TYPE_GROUP = 2;
	const TYPE_REWARD = 3;
	const TYPE_GIFT = 4;
	const TYPE_PLAN = 5;
	const TYPE_TUTOR = 6;
	
	public static $typeList = [
		self::TYPE_NORMAL => '普通订单',
		self::TYPE_GROUP => '拼团订单',
		self::TYPE_REWARD => '活动赠送订单',
		self::TYPE_GIFT => '代言人赠送订单',
		self::TYPE_PLAN => '创业大赛订单',
		self::TYPE_TUTOR => '导师大赛订单'
	];
	
	public function getOrderTypeTextAttr($value, $data)
	{
		$value = $value ?: $data['order_type'];
		$list = self::$typeList;
		return $list[$value] ?? '';
	}
	
	public function getAreaTextAttr($value, $data)
	{
		$value = $value ?: $data['area'];
		$list = \app\admin\model\User::$areaList;
		return $list[$value] ?? '';
	}
	
	const PAY_STATUS_WAIT = 0;
	const PAY_STATUS_Y = 1;
	const PAY_STATUS_REFUND = 2;
	const PAY_STATUS_REFUND_FAIL = 3;
	
	public static $payStatusList = [
		self::PAY_STATUS_Y => '已支付',
		self::PAY_STATUS_WAIT => '待支付',
		self::PAY_STATUS_REFUND => '已退款',
		self::PAY_STATUS_REFUND_FAIL => '退款失败'
	];
	
	public function getPayStatusTextAttr($value, $data)
	{
		$value = $value ?: $data['pay_status'];
		$list = self::$payStatusList;
		return $list[$value] ?? '';
	}
	
	const SHIPPING_STATUS_WAIT = 0;
	const SHIPPING_STATUS_SIGN = 1;
	const SHIPPING_STATUS_REFUND = 2;
	
	public static $shippingStatusList = [
		self::SHIPPING_STATUS_SIGN => '已签收',
		self::SHIPPING_STATUS_REFUND => '已退货',
		self::SHIPPING_STATUS_WAIT => '已发货'
	];
	
	public function getShippingStatusTextAttr($value, $data)
	{
		$value = $value ?: $data['shipping_status'];
		$list = self::$shippingStatusList;
		return $list[$value] ?? '';
	}
	
	const CANCEL_REASON_TIME = 1;
	const CANCEL_REASON_USER = 2;
	const CANCEL_REASON_GROUP_FAIL = 3;
	
	public static $cancelReasonList = [
		self::CANCEL_REASON_TIME => '超时取消',
		self::CANCEL_REASON_USER => '用户取消',
		self::CANCEL_REASON_GROUP_FAIL => '拼团人数未满'
	];
	
	public function getCancelReasonTextAttr($value, $data)
	{
		$value = $value ?: $data['canceL_reason'];
		$list = self::$cancelReasonList;
		return $list[$value] ?? '';
	}
	
	const SIGN_TYPE_SELF = 1;
	const SIGN_TYPE_SHIPPING = 2;
	
	public static $signTypeList = [
		self::SIGN_TYPE_SELF => '门店自提',
		self::SIGN_TYPE_SHIPPING => '快递'
	];
	
	public function getSignTypeTextAttr($value, $data)
	{
		$value = $value ?: $data['sign_type'];
		$list = self::$signTypeList;
		return $list[$value] ?? '';
	}
	
	const REBATE_NULL = 0;
	const REBATE_CAL = 1;
	const REBATE_WAIT = 2;
	const REBATE_DONE = 3;
	const REBATE_CLOSE = 4;
	const REBATE_NULL_REBATE = 5;
	
	public static $rebateList = [
		self::REBATE_CAL => '计算中',
		self::REBATE_NULL => '待付款',
		self::REBATE_WAIT => '待结算',
		self::REBATE_DONE => '已返利',
		self::REBATE_CLOSE => '已关闭',
		self::REBATE_NULL_REBATE => '无返利'
	];
	
	public function getRebateStatusTextAttr($value, $data)
	{
		$value = $value ?: $data['rebate_status'];
		$list = self::$rebateList;
		return $list[$value] ?? '';
	}
	
	public function getPayTimeTextAttr($value, $data)
	{
		$value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getShippingTimeTextAttr($value, $data)
	{
		$value = $value ? $value : (isset($data['shipping_time']) ? $data['shipping_time'] : '');
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getSignTimeTextAttr($value, $data)
	{
		$value = $value ? $value : (isset($data['sign_time']) ? $data['sign_time'] : '');
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	protected function setPayTimeAttr($value)
	{
		return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
	}
	
	protected function setShippingTimeAttr($value)
	{
		return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
	}
	
	protected function setSignTimeAttr($value)
	{
		return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
	}
	
	public function user()
	{
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function recommend()
	{
		return $this->belongsTo('user', 'recommend_user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function destruct()
	{
		return $this->belongsTo('agentShop', 'destruct_agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function shop()
	{
		return $this->belongsTo('agentShop', 'shop_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function warehouse()
	{
		return $this->belongsTo('agentShop', 'warehouse_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function center()
	{
		return $this->belongsTo('agentShop', 'center_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function theater()
	{
		return $this->belongsTo('agentShop', 'theater_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 获取订单列表
	 * @param $userId
	 * @param int $page
	 * @param string $status
	 * @param string $type
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getOrderList($userId, $page = 1, $status = '', $type = '')
	{
		$where = [
			'user_id' => $userId,
			'is_delete' => 0
		];
		
		strlen($status) > 0 && $where['status'] = $status;
		$type && $where['order_type'] = $type;
		
		$count = $this->where($where)->count();
		$orders = $this->where($where)
			->order(['update_time' => 'desc'])
			->page($page)
			->select();
		
		$list = [];
		if ($orders) {
			foreach ($orders as $item) {
				$item = $item->toArray();
				$goods = Db::name('orderGoods')
					->where(['order_id' => $item['id']])
					->select();
				foreach ($goods as &$good) {
					$good['goods_info'] = json_decode($good['goods_info'], true);
				}
				
				$item['goods'] = $goods;
				$list[] = $item;
			}
		}
		
		return [
			'total' => $count,
			'list' => $list
		];
	}
	
	
	public function addOrder($userId, $data, $type = 1)
	{
		
		//商品
		$goods = Db::name('goods')->alias('g')
			->join('goodsSpec s', 'g.id = s.goods_id and s.id = \'' . $data['goods_spec_id'] . '\'', 'left')
			->where(['g.id' => $data['goods_id']])
			->field('g.*, s.id as spec_id, s.price as spec_price, s.store_count as spec_store, s.image as spec_image, s.name as spec_name, s.group_rebate spec_rebate')
			->find();
		
		if (!$goods) {
			$this->error = '请选择要购买的商品';
			return false;
		}
		
		if ($goods['status'] != Goods::STATUS_SALE) {
			$this->error = '商品已下架';
			return false;
		}
		$number = $data['number'];
//		$goodsStore = $goods['spec_store'] ? $goods['spec_store'] : $goods['number_store'];
//
//		if($number > $goodsStore) {
//			$this->error = '库存不足';
//			return false;
//		}
		$goodsAmount = $goods['spec_price'] ? $goods['spec_price'] : $goods['price'];
		$offerAmount = 0;
		$couponAmount = 0;
		
		$user = User::get($userId);
		$levelIds = array_filter(explode(',', $goods['buy_level']));
		if ($levelIds && !in_array($user['level'], $levelIds)) {
			$levelList = \app\admin\model\User::$levelList;
			$levelText = '';
			foreach ($levelIds as $level) {
				$levelText .= $levelList[$level] . ' ';
			}
			$this->error = '该商品只允许' . $levelText . '购买，请先开通对应等级';
			return false;
		}
		
		if ($goods['min_number'] > 0 && $number < $goods['min_number']) {
			$this->error = '最少购买数量为' . $goods['min_number'];
			return false;
		}
		
		
		$amount = ($goodsAmount * $number) - $offerAmount - $couponAmount;
		$buyType = $data['buy_type'] ?? 'buy';
		
		$orderType = self::TYPE_NORMAL;
		
		
		//每个商品进行中的拼团只能有一个
		if ($buyType == 'group' || $buyType == 'join') {
			
			$goodsRow = Db::name('orderGoods')->alias('og')
				->join('order o', 'og.goods_id = o.id', 'left')
				->where([
					'og.goods_id' => $data['goods_id'],
					'o.user_id' => $userId,
					'o.order_type' => self::TYPE_GROUP,
					'o.status' => self::STATUS_GROUP
				])
				->find();
			
			
			if ($goodsRow) {
				$this->error = '该商品你有进行中的拼团';
				return false;
			}
			
			$orderType = self::TYPE_GROUP;
		}
		
		
		$groupId = $data['group_id'] ?? '';
		
		if ($groupId) {
			$group = Db::name('orderGroup')->find($groupId);
			if (!$group) {
				$this->error = '要参与的团不存在';
				return false;
			}
			
			if ($group['status'] != 1) {
				$this->error = '该团已结束拼团';
				return false;
			}
		}
		
		
		if ($type == 1) {
			return [
				'amount' => $amount,
				'number' => $number,
				'goods' => $goods
			];
		}
		
		
		$this->startTrans();
		try {
			
			$activityId = '';
			//活动商品，检测是创业大赛还是导师大赛
			if ($goods['is_activity']) {
				$activityRes = OrderService::getOrderTypeByActivity($goods['id']);
				if ($activityRes !== false) {
					$orderType = $activityRes['type'];
					$activityId = $activityRes['id'];
					
					if($orderType == Order::TYPE_PLAN) {
						$team = Db::name('teamMember')
							->where([
								'business_plan_id' => $activityId,
								'user_id' => $userId,
								'status' => TeamMember::STATUS_NORMAL])
							->find();
						if($team) {
							throw new Exception('你已参与此活动，不能购买此商品');
						}
					}
				}
			}
			
			$user = \app\admin\model\User::get($userId);
			
			$recommendUserId = $data['recommend_user_id'] ?: $user['recommend_user_id'];
			if ($buyType == 'group') {
				$groupModel = new OrderGroup();
				$groupRes = $groupModel->isUpdate(false)
					->save([
						'user_id' => $userId,
						'number' => 0,
						'recommend_user_id' => $recommendUserId,
					]);
				
				if (!$groupRes) {
					throw new Exception('创建团出错');
				}
				
				$groupId = $groupModel->getLastInsID();
			}
			
			$signType = !empty($data['sign_type']) ? $data['sign_type'] : 1;
			if ($signType == 2 && empty($data['address_id'])) {
				throw new Exception('请选择收货地址');
			}
			
			$res = $this->isUpdate(false)
				->save([
					'user_id' => $userId,
					'order_no' => time() . mt_rand(10000, 99999),
					'goods_amount' => $goodsAmount * $number,
					'offer_amount' => $offerAmount,
					'coupon_amount' => $couponAmount,
					'amount' => $amount,
					'number' => $number,
					'remark' => $data['remark'] ?? '',
					'group_id' => $groupId,
					'order_type' => $orderType,
					'code' => $userId . strrev(date('YmdHis')),
					'recommend_user_id' => $recommendUserId,
					'area' => $user['area'] ?: \app\admin\model\User::AREA_OTHER,
					'sign_type' => $signType,
					'activity_id' => $activityId,
					'center_shipping' => $goods['center_shipping']
				]);
			
			if (!$res) {
				throw new Exception('添加订单出错');
			}
			
			$orderId = $this->getLastInsID();
			
			$goods['spec_id'] = $goods['spec_id'] ?: 0;
			
			$goodsData = [
				'order_id' => $orderId,
				'goods_id' => $data['goods_id'],
				'number' => $number,
				'last_number' => $number,
				'amount' => ($goods['spec_price'] ?: $goods['price']) * $number,
				'spec_name' => $goods['spec_name'],
				'recommend_user_id' => $user['recommend_user_id'] ? $user['recommend_user_id'] : '',
				'goods_info' => json_encode($goods),
				'create_time' => time(),
				'update_time' => time(),
			];
			
			$goodsRes = Db::name('orderGoods')->insert($goodsData);
			if (!$goodsRes) {
				throw new Exception('添加订单商品出错');
			}
			
			//快递的
			if ($signType == 2) {
				$address = Db::name('address')
					->where(['user_id' => $userId, 'id' => $data['address_id'], 'status' => Address::STATUS_NORMAL])
					->find();
				if (!$address) {
					throw new Exception('收货地址不存在');
				}
				
				$address['order_id'] = $orderId;
				$addressModel = new OrderAddress();
				unset($address['id']);
				$addressRes = $addressModel->allowField(true)->isUpdate(false)->save($address);
				if (!$addressRes) {
					throw new Exception('添加收货地址出错');
				}
			}
			
			
			$this->commit();
			return [
				'id' => $orderId,
				'amount' => $amount
			];
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			$this->rollback();
			return false;
		}
	}
	
	/**
	 * 支付成功
	 * @param $id 订单ID
	 * @param $transactionId 流水号
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function paySuccess($id, $transactionId)
	{
		$order = $this->find($id);
		if (!$order) {
			$this->error = '订单不存在';
			return false;
		}
		
		if ($order['status'] != self::STATUS_WAIT) {
			$this->error = '非待支付订单';
			return false;
		}
		
		$this->startTrans();
		try {

//			if($order['recommend_user_id']) {
//				$bindRecommendUserIdRes = UserService::bindRecommendUserId($order['user_id'], $order['recommend_user_id']);
//				if(!$bindRecommendUserIdRes) {
//					$this->error = '绑定推荐人出错';
//					return false;
//				}
//			}
			
			
			//正常订单状态自取改为待核销,快递改为待发货，拼团订单改为销售中
			$status = $order['sign_type'] == self::SIGN_TYPE_SELF ? self::STATUS_SIGN : self::STATUS_WAIT_SHIPPING;
			$rebateStatus = self::REBATE_CAL;
			
			if ($order['order_type'] == self::TYPE_GROUP) {
				$status = self::STATUS_GROUP;
				$rebateStatus = self::REBATE_NULL;
			}
			//更改订单状态
			$res = $this->save(
				[
					'status' => $status,
					'pay_status' => self::PAY_STATUS_Y,
					'pay_time' => time(),
					'transaction_no' => $transactionId,
					'rebate_status' => $rebateStatus,
				],
				['id' => $id]);
			
			if (!$res) {
				throw new Exception('更改订单状态出错');
			}
			
			
			$this->commit();
			
			//加入队列
			Queue::addTask('orderSuccess', ['id' => $id]);
			//给上级发订单库存消息
			Queue::addTask('agentOrderTips', ['id' => $id]);
			//添加检测满3送1活动
			Queue::addTask('checkActivityGift', ['id' => $id]);
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * 签收订单
	 * @param $id
	 * @param string $userId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function sign($id, $userId = '')
	{
		
		$where['id'] = $id;
		$userId && $where['user_id'] = $userId;
		$order = $this->where($where)->find();
		
		if (!$order) {
			$this->error = '订单不存在';
			return false;
		}
		if ($order['status'] != self::STATUS_WAIT_SIGN) {
			$this->error = '非待签收订单';
			return false;
		}
		
		$this->startTrans();
		try {
			$res = $this->save([
				'status' => self::STATUS_SUCCESS,
				'sign_time' => time(),
				'shipping_status' => self::SHIPPING_STATUS_SIGN
			], ['id' => $id]);
			
			if (!$res) {
				throw new Exception("更改订单状态出错");
			}

//			$model = new Commission();
//			$commissionRes = $model->rebate($id);
//			if(!$commissionRes) {
//				throw new Exception('添加佣金出错'.$model->getError());
//			}
			
			if ($order['rebate_status'] == Order::REBATE_WAIT) {
				//更改佣金状态为已发入
				$commissionModel = new Commission();
				$commissionRes = $commissionModel->send($order['id']);
				if (!$commissionRes) {
					throw new Exception('更改返利状态出错');
				}
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			$this->rollback();
			return false;
		}
		
	}
	
	
	/**
	 * 取消订单
	 * @param $id
	 * @param $reason
	 * @param string $userId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function cancel($id, $reason, $userId = '')
	{
		$where['id'] = $id;
		$userId && $where['user_id'] = $userId;
		$order = $this->where($where)->find();
		
		if (!$order) {
			$this->error = '订单不存在';
			return false;
		}
		if ($order['status'] != self::STATUS_WAIT) {
			$this->error = '订单不可取消';
			return false;
		}
		
		$this->startTrans();
		try {
			$res = Db::name('order')
				->where(['id' => $id])
				->update([
					'status' => self::STATUS_CLOSE,
					'close_reason' => $reason,
					'update_time' => time()
				]);
			
			if (!$res) {
				throw new Exception("更改订单状态出错" . $this->getLastSql());
			}
			
			//添加商品库存
			$goods = Db::name('orderGoods')
				->where(['order_id' => $id])
				->field('id, goods_id, number, goods_info')
				->select();
			foreach ($goods as $good) {
				$goodsInfo = json_decode($good['goods_info'], true);
				$good['goods_spec_id'] = $goodsInfo['spec_id'];
				if ($good['goods_spec_id']) {
					$numRes = Db::name('goodsSpec')
						->where(['id' => $good['goods_spec_id']])
						->setInc('store_count', $good['number']);
				} else {
					$numRes = Db::name('goods')
						->where(['id' => $good['goods_id']])
						->setInc('number_store', $good['number']);
				}
				if ($numRes === false) {
					throw new Exception('添加商品库存出错');
				}
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			$this->rollback();
			return false;
		}
	}
	
	/**
	 * 核销订单
	 * @param $order 订单信息
	 * @param $agent 核销点信息
	 * @param $force 库存不足是否继续核销
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function destructOrder($order, $agent, $force)
	{
		
		$goods = Db::name('orderGoods')
			->where(['order_id' => $order['id']])
			->find();
		$goodsInfo = json_decode($goods['goods_info'], true);
		$goodsId = $goods['goods_id'];
		$specId = $goodsInfo['spec_id'];
		$number = $goods['last_number'];
		
		//减少库存
		$stockModel = new AgentStock();
		$stock = $stockModel->where([
			'user_id' => $agent['user_id'],
			'goods_id' => $goodsId,
			'spec_id' => $specId
		])->find();
		
		if (!$stock || $stock['number'] == 0) {
			$this->error = '你没有该商品的库存，不可核销!';
			return false;
		}
		
		if ($stock['number'] < $number && $force == 0) {
			$this->error = '库存不足，当前库存' . $stock['number'] . ',是否继续核销部分商品？';
			return -1;
		}
		
		$this->startTrans();
		try {
			
			
			if ($stock['number'] >= $number) {
				//更改订单状态
				$orderRes = Db::name('order')
					->where(['id' => $order['id']])
					->update([
						'status' => Order::STATUS_SUCCESS,
						'destruct_agent_id' => $agent['id'],
						'sign_time' => time(),
						'update_time' => time()
					]);
				
				if (!$orderRes) {
					throw new Exception('更改订单记录出错');
				}
			} else {
				//部分核销，更改核销码
				$orderRes = Db::name('order')
					->where(['id' => $order['id']])
					->update(['code' => $order['user_id'] . strrev(date('YmdHis')), 'update_time' => time()]);
			}
			
			$number = $stock['number'] >= $number ? $number : $stock['number'];
			
			if (!$orderRes) {
				throw new Exception('更改订单记录出错');
			}
			
			//减少数量
			$goodsRes = Db::name('orderGoods')->where(['id' => $goods['id']])->setDec('last_number', $number);
			if (!$goodsRes) {
				throw new Exception('更改订单剩余数量出错');
			}
			
			$stockRes = $stockModel->add($agent['user_id'], $agent['id'], $goodsId, $specId, -$number);
			if (!$stockRes) {
				throw new Exception('减少库存出错');
			}
			
			//添加库存记录
			$recordModel = new AgentStockRecord();
			$recordRes = $recordModel->addRecord($agent['user_id'], $goodsId, $specId, $recordModel::TYPE_DESTRUCT,
				$number, '订单取货核销');
			if (!$recordRes) {
				throw new Exception('添加库存记录出错');
			}
			
			//添加核销记录
			$shipModle = new AgentShip();
			$shopRes = $shipModle->addRecore($order['id'], $agent['id'], $goodsId, $specId, $number, $order['code']);
			if (!$shopRes) {
				throw new Exception('添加核销记录出错');
			}
			
			//获取设置信息(优先是单独设置的规则）
			$setting = Db::name('goodsRule')->where(['goods_id' => $goods['goods_id']])->find();
			//其它地区核销规则
			if ($order['area'] == \app\admin\model\User::AREA_OTHER) {
				//发核销佣金, 核销点有5元，核销点上级提货点有5元，提货点的上级提货点算自己
				if (!$setting) {
					$setting = Db::name('setting')->find();
				}
				if ($setting && ($setting['shop_ship_amount'] > 0 || $setting['warehouse_amount'] > 0)) {
					$commissionModel = new Commission();
					//场景店,自己5元，归属提货点5元
					if ($agent['role'] == \app\admin\model\User::LEVEL_SHOP) {
						
						if ($setting['shop_ship_amount'] > 0) {
							$shopRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'],
								$goodsId, $goods['id'], $setting['shop_ship_amount'] * $number, '场景店核销奖励',
								$commissionModel::TYPE_GOODS);
							
							if (!$shopRes) {
								throw new Exception('添加场景店核销奖励出错');
							}
						}
						
						if ($setting['warehouse_amount'] > 0 && $agent['warehouse_id']) {
							$warehouse = Db::name('agentShop')->find($agent['warehouse_id']);
							if ($warehouse && $warehouse['status'] == AgentShop::STATUS_Y) {
								$msg = '提货点下级核销奖励';
								$warehouseCommission = $setting['warehouse_amount'] * $number;
								$warehouseUserId = $warehouse['user_id'];
								//是连锁店，钱给上给
								if ($warehouse['chain_user_id']) {
									$warehouseUserId = $warehouse['chain_user_id'];
									$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'], $order['id'],
										$warehouseCommission, ChainFunds::TYPE_DESTORY);
									if (!$fundsRes) {
										throw new Exception('添加连锁佣金记录出错');
									}
									$msg = '连锁店下级提货点核销奖励';
								}
								
								$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'],
									$order['id'], $goodsId, $goods['id'], $warehouseCommission, $msg,
									$commissionModel::TYPE_GOODS);
								if (!$warehouseRes) {
									throw new Exception('添加提货点奖励出错');
								}
							}
						}
					} else {
						if ($agent['role'] == \app\admin\model\User::LEVEL_WAREHOUSE) {
							//销售是场景店，自己拿了核销和核销上级的钱
							$warehouse = $agent;
							//场景店
							if ($warehouse && $warehouse['role'] == \app\admin\model\User::LEVEL_WAREHOUSE) {
								$warehouseCommission = ($setting['warehouse_amount'] + $setting['shop_ship_amount']) * $number;
								$warehouseUserId = $warehouse['user_id'];
								if ($warehouse['chain_user_id']) {
									$warehouseUserId = $warehouse['chain_user_id'];
									$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'], $order['id'],
										$warehouseCommission, ChainFunds::TYPE_DESTORY);
									if (!$fundsRes) {
										throw new Exception('添加连锁佣金记录出错');
									}
									$msg = '连锁店下级提货点核销奖励';
								}
								
								$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'],
									$order['id'], $goodsId, $goods['id'], $warehouseCommission, $msg,
									$commissionModel::TYPE_GOODS);
								if (!$warehouseRes) {
									throw new Exception('添加提货点奖励出错');
								}
								
							}
						}
					}
					
					
				}
			} else {
				
				if (!$setting) {
					$setting = Db::name('ruleSz')->find();
				}
				//深圳规则
				if ($setting) {
					if ($agent['role'] == \app\admin\model\User::LEVEL_WAREHOUSE) {
						//发核销佣金, 提货点自己核销有佣金
						if ($setting['warehouse_destroy'] > 0) {
							$commissionModel = new Commission();
							$warehouseCommission = $setting['warehouse_destroy'] * $number;
							$warehouseRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'],
								$goodsId, $goods['id'], $warehouseCommission, '提货点核销奖励(深圳)',
								$commissionModel::TYPE_GOODS);
							if (!$warehouseRes) {
								throw new Exception('添加提货点奖励出错');
							}
						}
					} else {
						if ($agent['role'] == \app\admin\model\User::LEVEL_SHOP) {
							//场景店核销上级有佣金
							if ($agent['center_id'] && $setting['shop_destroy'] > 0) {
								$center = AgentShop::get($agent['center_id']);
								$commissionModel = new Commission();
								$warehouseCommission = $setting['shop_destroy'] * $number;
								$warehouseRes = $commissionModel->rebate($center['user_id'], $order['user_id'],
									$order['id'], $goodsId, $goods['id'], $warehouseCommission, '场景点核销上级奖励(深圳)',
									$commissionModel::TYPE_GOODS);
								if (!$warehouseRes) {
									throw new Exception('添加场景点上级奖励出错');
								}
							}
						}
					}
				}
			}
			
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	/**
	 * 订单发佣金，记录销售数量，拼团发红包
	 * @param $orderId
	 * @return bool
	 */
	public function rebate($orderId)
	{
		
		
		try {
			$order = Db::name('order')->find($orderId);
			
			$goods = Db::name('orderGoods')->where(['order_id' => $orderId])->find();
			$goodsInfo = json_decode($goods['goods_info'], true);
			$userModel = new \app\admin\model\User();
			
			$saleCommission = 0;
			$orderNumber = $order['number'];
			//推荐人返利
			if ($order['recommend_user_id']) {
				$agentId = '';
				$promotionId = '';
				
				$recomendUser = Db::name('user')->find($order['recommend_user_id']);
				//获取设置信息
				$setting = Db::name('goodsRule')->where(['goods_id' => $goods['goods_id']])->find();
				if (!$setting) {
					$setting = Db::name('setting')->find();
				}
				
				$saleCommission = $setting['sale_amount'];
				if (!empty($setting['rebate_level'])) {
					$rebateLevel = array_filter(explode(',', $setting['rebate_level']));
					if (!in_array($recomendUser['level'], $rebateLevel)) {
						$saleCommission = 0;
					}
				}
				
				
				//正常的购买返利
				if ($setting && $orderNumber > 0 && $saleCommission > 0) {
					$commissionModel = new Commission();
					//如果推荐人是代言人,场景店和提货点,发展中心可以有5元
					if ($recomendUser['level'] == $userModel::LEVEL_PROMOTION) {
						$promotionInfo = Db::name('promotion')->alias('p')
							->join('agentShop a', 'p.agent_shop_id = a.id', 'left')
							->where(['p.user_id' => $order['recommend_user_id'], 'p.status' => Promotion::STATUS_Y])
							->field('p.id, a.user_id as agent_user_id, a.id as agent_id')
							->find();
						
						if ($promotionInfo) {
							//代言人返利
							$commission = $saleCommission * $orderNumber;
							$commissionRes = $commissionModel->rebate($order['recommend_user_id'], $order['user_id'],
								$orderId, $goods['goods_id'], $goods['id'], $commission, '代言人销售奖励');
							if (!$commissionRes) {
								throw new Exception('添加代言人销售佣金出错');
							}
						}
					} else {
						$agentInfo = Db::name('agentShop')
							->where(['user_id' => $order['recommend_user_id'], 'status' => AgentShop::STATUS_Y])
							->find();
						if ($agentInfo) {
							$agentId = $agentInfo['id'];
							
							//场景店销售奖励
							if (in_array($recomendUser['level'],
								[$userModel::LEVEL_SHOP, $userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_CENTER])) {
								
								$levelList = $userModel::$levelList;
								$shoCommission = $saleCommission * $orderNumber;
								
								//提货点销售奖励
								if ($recomendUser['level'] == $userModel::LEVEL_WAREHOUSE) {
									$warehouseUserId = $agentInfo['user_id'];
									if ($agentInfo['chain_user_id']) {
										$warehouseUserId = $agentInfo['chain_user_id'];
										$fundsRes = ChainFunds::addRecord($warehouseUserId, $agentInfo['id'], $orderId,
											$shoCommission, ChainFunds::TYPE_SELF);
										if (!$fundsRes) {
											throw new Exception('添加连锁佣金记录出错');
										}
									}
									
									$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'],
										$orderId,
										$goods['goods_id'], $goods['id'], $shoCommission,
										$agentInfo['chain_user_id'] ? '连锁下级提货点销售奖励' : '提货点销售奖励');
									if (!$warehouseRes) {
										throw new Exception('添加提货点销售佣金出错');
									}
								} else {
									$shopRes = $commissionModel->rebate($order['recommend_user_id'], $order['user_id'],
										$orderId, $goods['goods_id'], $goods['id'], $shoCommission,
										$levelList[$recomendUser['level']] . '销售奖励');
									if (!$shopRes) {
										throw new Exception('添加' . $levelList[$recomendUser['level']] . '销售佣金出错');
									}
								}
								
								
							}
							
						}
					}
				}
				
				
				$shopWhere = [];
				//更改订单的归属关系
				if ($recomendUser['level'] == 1) {
					//代言人资料
					$info = Db::name('promotion')->where(['user_id' => $recomendUser['id']])->find();
					if ($info) {
						
						if ($orderNumber > 0) {
							//加代言人的销量
							$promotionRes = Db::name('promotion')->where(['id' => $info['id']])
								->update([
									'sale_number' => $info['sale_number'] + $orderNumber,
									'order_number' => $info['order_number'] + 1,
									'sale_amount' => $info['sale_amount'] + $order['amount']
								]);
							
							if (!$promotionRes) {
								throw new Exception('添加代言人销售出错');
							}
							
							$promotionItemRes = SaleItem::addRow($orderId, $recomendUser['id'], $orderNumber);
							if (!$promotionItemRes) {
								throw new Exception('添加代言人销量记录出错');
							}
						}
						
						
						if ($info['agent_shop_id']) {
							$shopWhere['id'] = $info['agent_shop_id'];
						}
					}
				} else {
					$shopWhere['user_id'] = $order['recommend_user_id'];
				}
				
				if ($shopWhere) {
					$shop = Db::name('agentShop')->where($shopWhere)->find();
					if ($shop) {
						
						$data = [
							'shop_id' => $shop['role'] == $userModel::LEVEL_SHOP ? $shop['id'] : '',
							'warehouse_id' => $shop['role'] == $userModel::LEVEL_WAREHOUSE ? $shop['id'] : $shop['warehouse_id'],
							'center_id' => $shop['role'] == $userModel::LEVEL_CENTER ? $shop['id'] : $shop['center_id'],
							'theater_id' => $shop['role'] == $userModel::LEVEL_THEATER ? $shop['id'] : $shop['theater_id'],
						];
						
						
						$agentRes = Db::name('order')
							->where(['id' => $orderId])
							->update($data);
						if ($agentRes === false) {
							throw new Exception('记录订单归属出错');
						}
						
						
						//添加销售和金额
						$shopIds = array_filter(array_values($data));
						if ($shopIds) {
							$shopModel = new AgentShop();
							
							if ($orderNumber > 0) {
								foreach ($shopIds as $shopId) {
									$numRes = $shopModel->addNumber($shopId, $orderNumber, $order['amount'], 1,
										$orderId,
										$agentId, $promotionId);
									if (!$numRes) {
										throw new Exception('添加代理销售数量出错');
									}
								}
							}
						}
						
					}
				}
				
				
			}
			//添加商品销量
			$goodsRes = Db::name('goods')
				->where(['id' => $goods['goods_id']])
				->setInc('number_sale', $goods['number']);
			if (!$goodsRes) {
				throw new Exception('添加商品销量出错');
			}
			
			
			//拼团的发红包
			if ($order['order_type'] == self::TYPE_GROUP && $order['group_id']) {
				$rebateAmount = $goodsInfo['spec_rebate'] ? $goodsInfo['spec_rebate'] : $goodsInfo['group_rebate'];
				if ($rebateAmount > 0) {
					$redModel = new RedEnvelope();
					$redRes = $redModel->add($order['user_id'], $orderId, $goods['goods_id'], $goods['id'],
						$rebateAmount * $goods['number']);
					if (!$redRes) {
						throw new Exception('添加红包出错');
					}
				}
			}
			
			
			return true;
		} catch (ErrorException $e) {
			$this->error = $e->getMessage();
			return false;
		} catch (\Exception $e) {
			$this->error = $e->getMessage();
			return false;
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	/**
	 * 生成奖励订单
	 * @param $userId 用户ID
	 * @param $number 商品数量
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @param $orderType 订单类型
	 * @param $area 地区
	 * @param string $remark 备注
	 * @param string $recommendId 推荐人
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addRewardOrder(
		$userId,
		$number,
		$goodsId,
		$specId,
		$orderType,
		$area,
		$remark = '',
		$recommendId = '',
		$orderAmount = 0
	) {
		
		//商品
		$goods = Db::name('goods')->alias('g')
			->join('goodsSpec s', 'g.id = s.goods_id and s.id = \'' . $specId . '\'', 'left')
			->where(['g.id' => $goodsId])
			->field('g.*, s.id as spec_id, s.price as spec_price, s.store_count as spec_store, s.image as spec_image, s.name as spec_name, s.group_rebate spec_rebate')
			->find();
		
		if (!$goods) {
			$this->error = '赠送商品不存在';
			return false;
		}
		
		$user = User::get($userId);
		$goodsAmount = $goods['spec_price'] ? $goods['spec_price'] : $goods['price'];
		$res = $this->isUpdate(false)
			->save([
				'pay_status' => self::PAY_STATUS_Y,
				'pay_time' => time(),
				'user_id' => $userId,
				'order_no' => time() . mt_rand(10000, 99999),
				'goods_amount' => $goodsAmount * $number,
				'amount' => $orderAmount,
				'number' => $number,
				'remark' => $remark,
				'group_id' => '',
				'order_type' => $orderType,
				'code' => $userId . strrev(date('YmdHis')),
				'recommend_user_id' => $recommendId ?: $user['recommend_user_id'],
				'area' => $area,
				'status' => self::STATUS_SIGN,
				'rebate_status' => self::REBATE_CAL
			]);
		
		if (!$res) {
			$this->error = '添加订单出错';
			return false;
		}
		
		$orderId = $this->getLastInsID();
		
		
		$goods['spec_id'] = $specId;
		
		$goodsData = [
			'order_id' => $orderId,
			'goods_id' => $goodsId,
			'number' => $number,
			'last_number' => $number,
			'amount' => ($goods['spec_price'] ?: $goods['price']) * $number,
			'spec_name' => $goods['spec_name'],
			'recommend_user_id' => '',
			'goods_info' => json_encode($goods),
			'create_time' => time(),
			'update_time' => time(),
		];
		
		$goodsRes = Db::name('orderGoods')->insert($goodsData);
		if (!$goodsRes) {
			$this->error = '添加订单商品出错';
			return false;
		}
		
		//加入队列
		Queue::addTask('orderSuccess', ['id' => $orderId]);
		//给上级发订单库存消息
		Queue::addTask('agentOrderTips', ['id' => $orderId]);
		
		return true;
	}
}
